﻿using System;
using System.Diagnostics;
using System.Net;
using System.Threading.Tasks;
using Red.CommUtils;
using Red.CommUtils.Application;
using Red.Core.Network;
using Red.Core.Network.PacketNetwork;

namespace Red.Launcher.Interop
{
    public class Editor
    {
        public PacketNetworkManager Network { get; private set; }

        public ChannelFactory ChannelFactory { get; private set; }

        public IChannel Channel { get; private set; }
        
        public const int EDITOR_PORT = 37042;

        public Editor()
        {
            Network = new PacketNetworkManager( new RawTcpManager( ErrorHandler ) );
            ChannelFactory = new ChannelFactory( Network );
        }

        public async Task< bool > Connect()
        {
            TcpAddress address = new TcpAddress( IPAddress.Loopback, EDITOR_PORT );

            try
            {
                Channel = await ChannelFactory.OpenChannel( "editor", address );
            }
            catch( CommunicationException ex )
            {
                Debug.Print( $"Failed to open channel: {ex}" );

                return false;
            }

            return true;
        }

        void ErrorHandler( Exception ex )
        {
            Debug.Print( $"Connection Error: {ex}" );
        }
    }
}
